#include "bsp.h"
#include "bsp_tim5.h"

TIM_HandleTypeDef TIM2Handle;
//TIM_HandleTypeDef TIM5Handle;


uint16_t ms_camera_tim;
uint16_t ms_camera_stop;
extern uint8_t ms_camera_count ;
__weak void BSP_TIM2_Callback(void)
{
    return;
}

__weak void BSP_TIM5_Callback(void)
{
    return;
}


/*定时器回调函数*/
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    if(htim->Instance == TIM2)
    {
			  ms_camera_tim ++;
			  ms_camera_stop ++;
        BSP_TIM2_Callback();        
    }
		if(ms_camera_count>=1)
			HAL_GPIO_WritePin(Tigger_MD2_PORT, Tigger_MD2_PIN, GPIO_PIN_RESET);
    if(htim->Instance == TIM5)
    {
        BSP_TIM5_Callback();        
    }
}

/*
 * @brief  定时器配置
 * @input  ms：一次定时时间
 * @output 无 
 * @param  None
 * @retval None
 * 
 *TIM2, TIM3, TIM4, TIM5, TIM6, TIM7, TIM12 接在APB1(42M) 定时器工作时钟42*2 = 84M
 *TIM1, TIM8, TIM9, TIM10, TIM11            接在APB2(84M) 定时器工作时钟84*2 = 168M

 *Ft：定时器工作频率,单位:Mhz
 *arr：自动重装值。 psc：时钟预分频数  
 *定时器溢出时间计算方法:Tout = ((arr+1)*(psc+1))/Ft us.   
 *1000 =  ( 9+1 ) * ( 8399+1 ) / 84        
*/
void TIM2_Init(uint16_t ms)
{
    if(ms > 5000)                                          //防止定时器定时超限
    {
        ms = 5000;
    }
    TIM2Handle.Instance           = TIM2;
    TIM2Handle.Init.Prescaler     = 8399;                  
    TIM2Handle.Init.CounterMode   = TIM_COUNTERMODE_UP;    //向上计数
    TIM2Handle.Init.Period        = ms * 10 - 1;           //自动重装载值
    TIM2Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;//时钟分频因子

    if (HAL_TIM_Base_Init(&TIM2Handle) != HAL_OK)
    {
        _Error_Handler(__FILE__, __LINE__);
    }

    HAL_TIM_Base_Start_IT(&TIM2Handle);
}

/* TIM8 init function */

//void TIM5_Init(uint16_t ms)
//{
//    TIM5Handle.Instance           = TIM5;
//    TIM5Handle.Init.Prescaler     = 83;                  
//    TIM5Handle.Init.CounterMode   = TIM_COUNTERMODE_UP;    //向上计数
//    TIM5Handle.Init.Period        = ms;           //自动重装载值
//    TIM5Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;//时钟分频因子

//    if (HAL_TIM_Base_Init(&TIM5Handle) != HAL_OK)
//    {
//        _Error_Handler(__FILE__, __LINE__);
//    }

//    HAL_TIM_Base_Start_IT(&TIM5Handle);
//}


void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim)
{
    if(htim->Instance == TIM2)
    {
        __HAL_RCC_TIM2_CLK_ENABLE();
        HAL_NVIC_SetPriority(TIM2_IRQn, 3, 0);
        HAL_NVIC_EnableIRQ(TIM2_IRQn);
    }

   HAL_TIM5_Base_MspInit(htim);
		
}
